package utils;

/**
 * 金额转化工具类
 * @author bug-fsh
 */
public class MoneyCoverUtils {
    //数字大写
    private final static char [] NUMBER = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};
    //整数单位
    private final static char [] INTEGER_UNIT = {'元', '十', '佰', '仟', '万', '十', '佰', '仟', '万', '亿'};
    //小数单位
    private final static char [] DECIMAL_UNIT = {'角', '分'};

    /**
     * 整数金额转化中文大写
     * @param money int
     * @return String
     * @throws Exception
     */
    public static String converChinese(int money) throws Exception {
        if (money < 0) {
            throw new Exception("请核对金额，金额不能小于0");
        }
        StringBuffer converResult = new StringBuffer();
        StringBuffer moneyStr = new StringBuffer(String.valueOf(money));
        for (int i = 0 , j = moneyStr.length() - 1; i < moneyStr.length() && j >= 0; i++, j--) {
            converResult.append(NUMBER[CharUtils.charToNum(moneyStr.charAt(i))]);
            converResult.append(INTEGER_UNIT[j]);
        }
        handle(converResult);
        handleHeader(converResult);
        return converResult.toString();
    }

    /**
     * 小数金额转化中文大写
     * @param money double
     * @return String
     * @throws Exception
     */
    public static String converChinese(double money) throws Exception {
        if (money < 0) throw new Exception("请核对金额，金额不能小于0");
        String moneyStr = String.valueOf(money);
        StringBuffer converResult = new StringBuffer();
        String [] moneys = moneyStr.split("\\.");
        int integerMoney = Integer.valueOf(moneys[0]);
        converResult.append(converChinese(integerMoney));
        StringBuffer decmial = new StringBuffer(moneys[1]);
        for (int i = 0; i < decmial.length(); i++) {
            converResult.append(NUMBER[CharUtils.charToNum(decmial.charAt(i))]);
            converResult.append(DECIMAL_UNIT[i]);
        }
        handle(converResult);
        return converResult.toString();
    }

    private static void handle(StringBuffer stringBuffer) {
        StringUtils.replace(stringBuffer, "零亿", "零");
        StringUtils.replace(stringBuffer, "零万", "零");
        StringUtils.replace(stringBuffer, "零仟", "零");
        StringUtils.replace(stringBuffer, "零佰", "零");
        StringUtils.replace(stringBuffer, "零十", "零");
        StringUtils.replace(stringBuffer, "零零", "零");
        StringUtils.replace(stringBuffer, "零元", "元");
        StringUtils.replace(stringBuffer, "零角", "零");
        StringUtils.replace(stringBuffer, "零分", "");
    }
    private static void handleHeader(StringBuffer stringBuffer) {
    }

    public static void main(String [] args) throws Exception {
        System.out.println(converChinese(0.1));
    }
}
